#include "libavutil/avutil.h"
#include "libavformat/avformat.h"

//ffmpeg7
//提取h264 p11
// ./metedata xxx.avi out.h264
//播放  ffplay out.h264

int main(int argc, char **argv) {

    av_log_set_level(AV_LOG_DEBUG);
    if (argc < 3) {
        av_log(NULL, AV_LOG_ERROR, "Usage: %s <infileName> <outfileName> \n", argv[0]);
        return -1;
    }

    const char *inFileName = argv[1];
    const char *outFileName =  argv[2];

    AVFormatContext *inFmtCtx = NULL;
    int ret = avformat_open_input(&inFmtCtx, inFileName, NULL, NULL);
    if (ret != 0 ) {
        av_log(NULL, AV_LOG_ERROR, "open input format failed: %s\n", av_err2str(ret));
        return -1;
    }
    ret = avformat_find_stream_info(inFmtCtx, NULL);
    if (ret != 0) {
        av_log(NULL, AV_LOG_ERROR, "find input stream info failed: %s\n", av_err2str(ret));
        ret = -1;
        goto fail;
    }

    ret = av_find_best_stream(inFmtCtx, AVMEDIA_TYPE_VIDEO, -1, -1, NULL, 0);
    if (ret < 0) {
        av_log(NULL, AV_LOG_ERROR, "find best stream index failed.\n");
        goto fail;
    }
    int videoIndex = ret;
    FILE *dest_fp = fopen(outFileName, "wb+");
    if (dest_fp == NULL) {
        av_log(NULL, AV_LOG_ERROR, "open %s file failed.\n", outFileName);
        ret = -1;
        goto fail;
    }

    AVPacket *packet = av_packet_alloc();
    if (!packet) {
        av_log(NULL, AV_LOG_ERROR, "av_packet_alloc failed \n");
        goto fail;
    }

    while (av_read_frame(inFmtCtx, packet) == 0) {
        if (packet->stream_index == videoIndex) {
            int writeSize = fwrite(packet->data, 1, packet->size, dest_fp);
            if (writeSize != packet->size) {
                av_packet_unref(packet);
                ret = -1;
                break;
            }
        }
        av_packet_unref(packet);
    }

    


    fail:
        if (inFmtCtx) {
            avformat_close_input(&inFmtCtx);
        }
        if(dest_fp) {
            fclose(dest_fp);
        }

    return 0;
}